<?php

// +----------------------------------------------------------------------
// | Admin Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2024 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-admin
// | github 代码仓库：https://github.com/zoujingli/think-plugs-admin
// +----------------------------------------------------------------------

declare(strict_types=1);

namespace app\admin\controller;

use app\common\model\admin\AccountModel;
use app\common\model\paths\PlatformModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemAuth;
use think\admin\model\SystemBase;
use think\admin\model\SystemUser;
use think\admin\service\AdminService;

/**
 * 账户管理员
 * @class Queue
 * @package app\admin\controller
 */
class AccountUser extends Controller
{

    /**
     * 默认检测登陆后台用户
     *
     * @var bool
     */
    public $check_user = false;

    /**
     * 账户管理员
     * @auth true
     * @menu true
     * @login true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        SystemUser::mQuery()->layTable(function () {

            $this->title        = lang('账户管理员列表');//usertype

        }, static function (QueryHelper $query) {

            $query->whereIn('usertype', ['account','teacher', 'super'])->where('is_deleted', 0);

            $query->order('id', 'desc')->dateBetween('create_at')->equal('status,account_id')->like('username,nickname');
        });
    }


    protected function _index_page_filter (&$data)
    {
        $account_arr = AccountModel::mk()->where("1=1")->column('title', 'id');

        $usertype = ['account'=>lang('其他'),'teacher'=>lang('老师'), 'super' =>lang('超管')];

        foreach ($data as &$item) {

            $item['account_name'] = $account_arr[$item['account_id']] ?? '';
            $item['usertype']     = $usertype[$item['usertype']] ?? '';
        }
    }


    /**
     * 添加
     * @auth true
     * @return void
     */
    public function add ()
    {
        SystemUser::mForm();
    }

    /**
     * 编辑
     * @auth true
     * @return void
     */
    public function edit ()
    {
        SystemUser::mForm();
    }


    /**
     * 修改用户状态
     * @auth true
     */
    public function state()
    {

        SystemUser::mSave($this->_vali([
            'status.in:0,1'  => lang('状态值范围异常').'！',
            'status.require' => lang('状态值不能为空').'！',
        ]));
    }

    /**
     * 删除系统用户
     * @auth true
     */
    public function remove()
    {

        SystemUser::mDelete();
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {

        if ($this->request->isPost()) {

            // 检查资料是否完整
            empty($data['username']) && $this->error(lang('登录账号不能为空').'！');
            // 检查账号是否重复
            $user_obj = SystemUser::mk()->where('username', $data['username'])->where('is_deleted', 0);


            if ( isset($data['id']) && $data['id']) {
                $user_obj = $user_obj->where('id', '<>',$data['id']);
            }
            if ($user_obj->count() > 0) {
                $this->error(lang('账号已经存在，请使用其它账号')."！");
            }

            if (empty($data['password'])) {

                unset($data['password']);
            } else {
                $data['password'] = md5($data['password']);
            }

            //$data['usertype']  = 'account';
            $data['authorize'] = isset($data['authorize']) ? implode(',', $data['authorize']) : [];
        } else {

            $account = $data['account_id'] ?? $this->account_id;

            $this->auth_arr = SystemAuth::mk()->where('account_id', $account)->where('utype', 'account')->column('title', 'id') ;

            if ( !empty($data) ) {
                $data['authorize'] =  $data['authorize'] ? explode(',', $data['authorize'] ) : [];
            }

            $this->has_teacher_auther = AccountModel::mk()->where('id', $account)->whereRaw("find_in_set('".AccountModel::MODULE_SCHOOLS."', module)")->count();

        }
    }

    /**
     * 修改用户密码
     * @auth true
     */
    public function pass()
    {
        $this->_applyFormToken();
        if ($this->request->isGet()) {
            $this->verify = false;
            SystemUser::mForm('pass');
        } else {
            $data = $this->_vali([
                'id.require'                  => lang('用户ID不能为空').'！',
                'password.require'            => lang('登录密码不能为空').'！',
                'repassword.require'          => lang('重复密码不能为空').'！',
                'repassword.confirm:password' => lang('两次输入的密码不一致').'！',
            ]);
            $user = SystemUser::mk()->findOrEmpty($data['id']);
            if ($user->isExists() && $user->save(['password' => md5($data['password'])])) {
                // 修改密码同步事件处理
                $this->app->event->trigger('PluginAdminChangePassword', [
                    'uuid' => $data['id'], 'pass' => $data['password']
                ]);
                sysoplog('系统用户管理', "修改用户[{$data['id']}]密码成功");
                $this->success(lang('密码修改成功，请使用新密码登录').'！', '');
            } else {
                $this->error(lang('密码修改失败，请稍候再试').'！');
            }
        }
    }

    /**
     * 修改用户密码
     * @auth true
     */
    public function getRoleList ()
    {
        $account_id = $this->request->get('account_id');

        $list = SystemAuth::mk()->where('utype', 'account')->where('account_id', $account_id)->column('title', 'id');

        $this->success('成功', $list);
    }
}
